import { reactive } from "vue";
import { me, uploadHeadImage } from "@/api/auth/user";
import { ElMessage } from "element-plus";
import { useCurrentUserStore } from "@/stores/currentUser";
import { storeToRefs } from "pinia";
const store = useCurrentUserStore();
const { headImage } = storeToRefs(store);

export const _$ = reactive({
  state: {
    working: false,
  },
  requestParam: {
    id: null,
    birthday: "",
    email: "",
    gender: 0,
    name: "",
    phone: "",
    headImage: "",
  },
  headers: {
    Authorization: `Bearer ${localStorage.getItem("ats-user-token")}`,
  },
  responseParam: {},
  rules: reactive({}),
});

export const $ = {
  async onSubmit(formEl) {
    if (!formEl) {
      return;
    }
    await formEl.validate((valid, fields) => {
      if (valid) {
        uploadHeadImage(_$.requestParam).then((_) => {
          ElMessage({
            message: "更新成功",
            type: "success",
          });
        });
      }
    });
  },

  loadEdit() {
    me().then((data) => {
      _$.requestParam = data;
    });
  },

  onBeforeUpload(rawFile) {
    _$.state.working = true;
  },

  onUploadSuccess(response, uploadFile) {
    localStorage.setItem("ats-user-headImage", response.data);
    headImage.value = localStorage.getItem("ats-user-headImage");
    _$.requestParam.headImage = headImage.value;
    _$.state.working = false;
  },

  clean() {
    _$.requestParam = {
      id: null,
      birthday: "",
      email: "",
      gender: 0,
      name: "",
      phone: "",
      headImage: "",
    };
  },
};

export const to = {};
